package org.nanfang.dao.impl;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.nanfang.dao.StaffDao;
import org.nanfang.entity.Staff;
import org.nanfang.util.DbUtil;
import org.nanfang.util.DruidUtil;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class StaffDaoimplDbUtils implements StaffDao {
    @Override
    public int insert(Staff staff) throws SQLException {
        String sql = "insert into staffs(name,age,phone,sta_pos) values (?,?,?,?)";
        QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());
        Object[] ob = {
                staff.getName(),staff.getAge(),staff.getPhone(),staff.getStaPos()
        };
        return qr.update(sql,ob);
    }

    @Override
    public int delete(int id) {
        String sql = "delete from staffs where id = ?";
        QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());
        try {
            return qr.update(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException("删除异常",e);
        }
    }

    @Override
    public int update(Staff staff) {
        String sql = "update staffs set name = ?,age = ?,phone = ?,sta_pos = ?,update_time = ? where id = ?";
        QueryRunner qr =new QueryRunner(DruidUtil.getDataSource());
        Object[] ob = {
                staff.getName(),staff.getAge(),staff.getPhone(),staff.getStaPos(),staff.getUpdateTime()
        };
        try {
            return qr.update(sql,ob);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Staff> selectByPage(int currentPage, int pageSize) {
        String sql = "select id,name,age,phone,sta_pos as staPos,add_time as addTime,update_time as updateTime from staffs limit ?,?" ;
        int limit = (currentPage-1) * pageSize ;

        QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());
        BeanListHandler<Staff> beanListHandler =
                new BeanListHandler<>(Staff.class) ;

        try {
            // ResultSetHandler
            // 执行查询，在 query 方法内部通过调用 rsh.handle(resultSet) 方法，
            // 实现把结果集转换为指定类型
            return qr.query(sql,beanListHandler,limit,pageSize) ;
        } catch (SQLException e) {
            throw new RuntimeException("分页查询异常",e);
        }
    }

    @Override
    public List<Staff> selectById(int id) {
        String sql = "select id,name,age,phone,sta_pos as staPos,add_time as addTime,update_time as updateTime from staffs where id=?" ;
        QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());
        try {
            return Collections.singletonList(qr.query(sql, new BeanHandler<>(Staff.class), id));
        } catch (SQLException e) {
            throw new RuntimeException("根据ID查询异常",e);
        }
    }
}
